//
//  AddressLinstViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/26.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Alamofire
import PKHUD
import SwiftyJSON
import Networking

protocol AddressLinstViewControllerDelegate: NSObjectProtocol {
    func selectedAddress(model: AddressModel)
}

class AddressLinstViewController: BaseViewController, BottomShadow, AddCornerUIRectCorner, UITableViewDataSource, UITableViewDelegate, AddressTableViewCellDelegate {
    
    let cellHeight: CGFloat = 85
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var mainTableView: UITableView!
    @IBOutlet weak var addressButton: UIButton!
    var addressDelegate: AddressLinstViewControllerDelegate?
    var datas:[AddressModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name(rawValue:"reloadAddress"), object: nil)
        setUI()
    }
    
    deinit {
        /// 移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func reloadData() {
        self.fetchData()
    }
    
    private func setUI() {
        titleLabel(text: "地址管理", "icon_address")
        setShadow(view: mainView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        addCornerWithView(aView: addressButton, aCorners: [.bottomRight, .bottomLeft], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        mainTableView.register(UINib(nibName: "\(AddressTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(AddressTableViewCell.self)")
        mainTableView.estimatedRowHeight = 100
        mainTableView.rowHeight = UITableViewAutomaticDimension
        self.fetchData()
    }
    
    // 获取内容
    func fetchData() -> Void {
        let requesturl = "\(BaseURL)\(addressListUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: nil ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        self.datas.removeAll()
                                        for subject in arr {
                                            let dic = subject.dictionary!
                                            let model = AddressModel(fromDic: dic)
                                            self.datas.append(model)
                                            
                                        }
                                        self.mainTableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    override func setNavigation() {
    }
    
    // MARK: - 添加地址
    @IBAction func addressTap(_ sender: UIButton) {
        let addressDetailVC = AddressDetailViewController(nibName: "\(AddressDetailViewController.self)", bundle: nil)
       addressDetailVC.titleLabel(text: "新建地址", nil)
        self.navigationController?.pushViewController(addressDetailVC, animated: true)
    }

    // MARK: - tableViewDatasource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(AddressTableViewCell.self)") as? AddressTableViewCell
        cell?.delegate = self
        cell?.defaultButtonParam(model: self.datas[indexPath.row])
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        addressDelegate?.selectedAddress(model: self.datas[indexPath.row])
        self.navigationController?.popViewController(animated: true)
    }
    
    //MARK: AddressTableViewDelegate
    func eidtTap(cell: AddressTableViewCell) {
        let addressDetailVC = AddressDetailViewController(nibName: "\(AddressDetailViewController.self)", bundle: nil)
        addressDetailVC.titleLabel(text: "编辑地址", nil)
        addressDetailVC.addressModel = self.datas[(self.mainTableView.indexPath(for: cell)?.row)!]
        self.navigationController?.pushViewController(addressDetailVC, animated: true)
    }
    
    func deleteTap(cell: AddressTableViewCell) {
        let indexPath = mainTableView.indexPath(for: cell)
        let id :String = self.datas[indexPath!.row].id!
        CustomShowAlertView().show(title: "确认删除该地址吗?") { (isSuccess) in
            if isSuccess {
                self.fetchDel(parameters: ["id":id], indexPath: indexPath! as NSIndexPath)
            }
        }
    }
    
    func defaultTap(cell: AddressTableViewCell) {
        let indexPath = mainTableView.indexPath(for: cell)
        let id :String = self.datas[indexPath!.row].id!
        self.fetchDefalut(parameters: ["id":id])
    }
    
    func fetchDefalut(parameters:[String:String]) -> Void {
        let requesturl = "\(BaseURL)\(addressDefaultUrlSet)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.fetchData()
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
    }
    
    func fetchDel(parameters:[String:String],indexPath:NSIndexPath) -> Void {
        let requesturl = "\(BaseURL)\(addressDelUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                        self.datas.remove(at: indexPath.row)
                                        self.mainTableView.deleteRows(at: [indexPath as IndexPath], with: .none)
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
    }

}
